package com.elitedatai.mchtest.manage.repository;

import com.elitedatai.mchtest.manage.model.entity.DeviceEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;

public interface DeviceRepository extends JpaRepository<DeviceEntity, Integer> {

    /**
     * 根据多个条件动态查询设备信息
     * @param deviceSn 设备序列号
     * @param deviceType 设备类型
     * @param subType 子类型
     * @param childSn 子设备序列号
     * @param domains 域列表
     * @param workspaceId 工作空间ID
     * @param boundStatus 绑定状态
     * @return 设备实体列表
     */
    @Query("SELECT d FROM DeviceEntity d WHERE " +
            "(:deviceSn IS NULL OR d.deviceSn = :deviceSn) AND " +
            "(:deviceType IS NULL OR d.deviceType = :deviceType) AND " +
            "(:subType IS NULL OR d.subType = :subType) AND " +
            "(:childSn IS NULL OR d.childSn = :childSn) AND " +
            "(:domains IS NULL OR d.domain IN :domains) AND " +
            "(:workspaceId IS NULL OR d.workspaceId = :workspaceId) AND " +
            "(:boundStatus IS NULL OR d.boundStatus = :boundStatus)")
    List<DeviceEntity> findDevicesByMultipleConditions(
            @Param("deviceSn") String deviceSn,
            @Param("deviceType") Integer deviceType,
            @Param("subType") Integer subType,
            @Param("childSn") String childSn,
            @Param("domains") List<Integer> domains,
            @Param("workspaceId") String workspaceId,
            @Param("boundStatus") Boolean boundStatus);

    Optional<DeviceEntity> findByDeviceSn(String deviceSn);

    int countByDeviceSn(String deviceSn);

    @Query("select d from DeviceEntity d where d.boundStatus=true and " +
            "(:domain is null or d.domain=:domain) and " +
            "(:workspaceId is null or d.workspaceId=:workspaceId)")
    Page<DeviceEntity> findDeviceByDomainAnWorkSpaceIdAndTrueBoundStatus(Integer domain, String workspaceId, PageRequest pageRequest);
}
